package com.key.filter;

import com.alibaba.fastjson.JSONObject;
import com.key.common.JwtResult;
import com.key.common.R;
import com.key.utils.JwtUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 过滤器：主要是拦截token，进行相关验证工作。
 */
public class OAuth2Filter extends AuthenticatingFilter {

    //暂时不重写createToken方法
    @Override
    protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        return null;
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        /**
         * 如何解决跨域请求中的OPTIONS请求：进行跨域请求的时候，并且请求头中有额外参数，比如token，客户端会先发送一个OPTIONS请求
         来探测后续需要发起的跨域POST请求是否安全可接受所以这个请求就不需要拦截
         */
        if(((HttpServletRequest) request).getMethod().equals(RequestMethod.OPTIONS.name())){
            return true;
        }
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
          return true;
//        HttpServletRequest request = (HttpServletRequest) servletRequest;
//        HttpServletResponse response = (HttpServletResponse) servletResponse;
//        //从客户端请求的header中获取token
//        String token = request.getHeader("Authorization");
//        String refreshToken = request.getHeader("RAuthorization");
//        //设置响应类型
//        response.setContentType("application/json;charset=utf-8");
//        //判断token是否空或者空串
//        R r = new R();
//        if(token == null || "".equals(token)){
//            r.setCode(401);
//            r.setMsg("invalid token");
//            response.getWriter().write(JSONObject.toJSONString(r));
//            response.getWriter().flush();
//            response.getWriter().close();
//            return false;
//        }
//        //2. 验证token是否合法
//        JwtResult jwtResult = JwtUtils.validateJwt(token);
//        if (jwtResult.isSuccess()){//合法
////            //解析token
////            Claims claims = JwtUtils.parseJWT(token);//token中的获得用户名 和 密码
////            //解析token获得getSubject
////            UsernamePasswordToken usernamePasswordToken = JSONObject.parseObject(claims.getSubject(),UsernamePasswordToken.class);
////            //执行登录
////            getSubject(request,response).login(usernamePasswordToken);
//            //执行登录 没有抛异常，就证明成功
//            return true;
//        }else{//token不合法
//            if(refreshToken == null || "".equals(refreshToken)){
//                r.setCode(401);
//                r.setMsg("invalid token");
//                response.getWriter().write(JSONObject.toJSONString(r));
//                response.getWriter().flush();
//                response.getWriter().close();
//                return false;
//            }else {
//                // 验证refreshToken是否合法
//                JwtResult jwtResult1 = JwtUtils.validateJwt(refreshToken);
//                if (jwtResult1.isSuccess()){
//                    r.setCode(201); //code201，调用刷新接口/refresh
//                    r.setMsg("刷新2个Token");
//                    response.getWriter().write(JSONObject.toJSONString(r));
//                    response.getWriter().flush();
//                    response.getWriter().close();
//                    return false;
//                }else {
//                    //3. token过期
//                    if(jwtResult.getErrCode() == JwtUtils.JWT_ERRCODE_EXPIRE){
//                        r.setCode(jwtResult.getErrCode());
//                        r.setMsg("token 过期");
//                    }
//                    //4. token不合法
//                    if(jwtResult.getErrCode() == JwtUtils.JWT_ERRCODE_FAIL){
//                        r.setCode(jwtResult.getErrCode());
//                        r.setMsg("token 不合法");
//                    }
//                }
//            }
//            response.getWriter().write(JSONObject.toJSONString(r));
//            response.getWriter().flush();
//            response.getWriter().close();
//            return false;
//        }
    }

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        HttpServletResponse res = (HttpServletResponse) response;
        res.setContentType("application/json;charset=utf-8");
        try {
            //处理登录失败的异常
            Throwable throwable = e.getCause() == null ? e : e.getCause();
            R r = new R();
            r.setCode(401);
            r.setMsg(throwable.getMessage());
            String json = JSONObject.toJSONString(r);
            res.getWriter().write(json);
            res.getWriter().flush();
            res.getWriter().close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return false;
    }
}
